import Request from './request'
import { configUrl } from '@/config'
import store from '@/store'
const http = new Request()

http.setConfig((config) => {
  /* 设置全局配置 */
  config.baseUrl = configUrl.baseUrl
  const systemInfo = uni.getSystemInfoSync()
  const systemInfoHeaders = {
    'device-name': systemInfo.brand, // 设备名称
    'User-Type': 'app',
    width: systemInfo.screenWidth, // 屏幕宽度
    height: systemInfo.screenHeight, // 屏幕高度
    os: systemInfo.platform, // 客户端平台
    'os-version': systemInfo.system // 操作系统版本
  }
  config.header = {
    ...config.header,
    ...systemInfoHeaders
  }
  return config
})

http.interceptor.request(
  (config) => {
    // 动态获取config配置
    config.baseUrl = configUrl.baseUrl
    // 传递token
    const token = store.getters.token || null
    const tokenName = 'Authorization'
    if (token) {
      config.header[tokenName] = token
    } else if (config.header[tokenName]) {
      delete config.header[tokenName]
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

http.interceptor.response(
  (response) => {
    // token 校验不通过重新登录
    if (response.data && (response.data.code == 401 || response.data.code == 403)) {
      uni.showToast({
        title: response.data.msg || response.data.message,
        icon: 'none',
        duration: 5000
      })
      setTimeout(() => {
        store.dispatch('LogOut')
        uni.reLaunch({
          url: '/pages/login/index'
        })
      }, 1500)
    }
    return response.data
  },
  (error) => {
    if (error.statusCode !== 200) {
      if (error.data && (error.data.message || error.data.msg)) {
        uni.showToast({
          title: error.data.message || error.data.msg,
          icon: 'none',
          duration: 5000
        })
        // token 校验不通过重新登录
        if (
          (error.statusCode == 401 || error.statusCode == 403) &&
          error.config.url.indexOf('/auth/login/slide') === -1
        ) {
          setTimeout(() => {
            store.dispatch('LogOut')
            uni.reLaunch({
              url: '/pages/login/index'
            })
          }, 1500)
        }
      } else {
        uni.showToast({
          title: `${error.statusCode}服务器异常`,
          icon: 'none',
          duration: 5000
        })
      }
    }
    return error
  }
)

export { http as request }
